package cn.leonis.leetcode;

/**
 * @Author Tobi
 * @Date 2021-12-10 下午5:38
 * 删除链表中的倒数第几个节点
 * leetcode19
 */
public class RemoveNodeFromListSolution {

    public static void main(String[] args) {

    }

    /**
     * 解法：双指针法，指针相差n个步骤，如果快的指针到达末端，说明慢指针在倒数位置
     * @param head
     * @param n
     * @return
     */
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head, fast = head;
        //先让它几步
        for (int i = 0; i < n; i++) {
            fast = fast.next;
        }
        if (fast == null) {
            return head.next;
        }

        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        slow.next = slow.next.next;
        return head;
    }
}
